import React, { Fragment, useState } from 'react';
import { Col, Checkbox, Popover, Empty, List, Row, Pagination, Card } from 'antd';
import moment from 'moment';
import { onImgError } from '@/utils/utils';
import { TIMEFORMAT } from '@/utils/const';

import styles from '../Samples.less';

export type ImgInfoProps = {
  id?: number | string;
  imageSize?: number;
  path?: string;
  url: string;
  thumbUrl?: string;
}

export type ImgLabelTagProps = {
  id: number | string;
  labelName: string;
  imageLabelTagAttrVals?: any;
}

export type ImgLabelShapes = {
  labelName: string;
  labelColor: string;
  points: number[];
}

export type ImgProps = {
  id: string | number;
  imageTaskId: number | string;
  imageSubTaskId: number | string;
  image: ImgInfoProps;
  imageLabelShapes: ImgLabelShapes[];
  imageLabelTags: ImgLabelTagProps[];
  assignee: string;
  createdAt: number | string;
  updatedAt: number | string;
  isAnnotated: boolean;
  imageId: string | number;
}

interface Props {
  imgs: ImgProps[];
  checkedKeys: (number | string)[];
  onCheckboxChange: (e: any, item: ImgProps) => void;
  onImageClick: (item: ImgProps) => void;
  pagination: {
    current: number;
    pageSize: number;
  };
  onPageChange: (current: number, pageSize?: number) => void;
  loading: boolean;
  taskId: string | number;
}

interface ImgLoadedProps {
  [key: string]: boolean;
}

const SamplesImages: React.FC<Props> = props => {
  const { imgs, checkedKeys, onCheckboxChange, onImageClick, pagination, onPageChange, loading, taskId } = props;
  const [imgLoaded, setImgLoaded] = useState<ImgLoadedProps>({});

  const getImgDetail = (record: ImgProps) => {
    const data = [
      `文件名称：${record.image.path}`,
      `文件格式：${record.image.path?.split('.').pop()}`,
      `文件大小：${((record.image.imageSize as number) / 1024) > 1024 ? ((record.image.imageSize as number) / 1024 / 1024).toFixed(2) + 'M' : ((record.image.imageSize as number) / 1024).toFixed(2) + 'kb'}`,
      `创建时间：${moment(record.createdAt).format(TIMEFORMAT)}`,
      `标注状态：${record.isAnnotated ? '已标注' : '未标注'}`,
      `标注员：${record.assignee || ''}`,
      `标注时间：${record.isAnnotated ? moment(record.updatedAt).format(TIMEFORMAT) : ''}`,
    ]
    return (
      <List
        size='small'
        dataSource={data}
        renderItem={item => <List.Item>{item}</List.Item>}
      />
    )
  };

  return (
    <Card loading={loading}>
      <Row className={styles.row}>
        {imgs?.length > 0
          ? imgs.map(item => (
            <Col key={item.id} sm={12} md={8} lg={6} xl={4} className={styles.col}>
              <div className={styles.coverBox}>
                {imgLoaded[item.id]
                  ? (
                    <Fragment>
                      <Checkbox
                        className={`${styles.checkbox} ${checkedKeys.length ? styles.showCheckbox : ''}`}
                        onChange={(e) => onCheckboxChange(e, item)}
                        checked={checkedKeys.findIndex(i => taskId ? i === item.imageId : i === item.id) !== -1}
                      ></Checkbox>
                      <Popover
                        title='图片信息'
                        content={() => getImgDetail(item)}
                        color='#fff'
                        placement='rightTop'
                        overlayClassName={styles.imgInfo}
                      >
                        <img
                          alt={item.image.path}
                          src={item.image.thumbUrl || item.image.url}
                          onClick={() => onImageClick(item)}
                          onError={onImgError}
                        />
                      </Popover>
                    </Fragment>
                  ) : (
                    <div className={styles.imgLoading}>
                      图片正在加载，请耐心等待
                      <img
                        alt={item.image.path}
                        src={item.image.thumbUrl || item.image.url}
                        className={styles.hiddenImg}
                        onLoad={() => setImgLoaded({ ...imgLoaded, [item.id]: true })}
                      />
                    </div>
                  )
                }
              </div>
            </Col>
          )) : <Empty style={{ width: '100%' }} description='暂无图片' />
        }
      </Row>
      {imgs?.length > 0 &&
        <Row className={styles.pagination}>
          <Pagination
            {...pagination}
            showQuickJumper
            pageSizeOptions={['12', '24', '36', '48', '60']}
            showSizeChanger={true}
            showTotal={total => `总共 ${total} 条`}
            onChange={onPageChange}
          />
        </Row>
      }
    </Card>
  )
}

export default SamplesImages;